package program;
import kernel.ProcessManager;
import kernel.ProcessMemory;
import kernel.exception.OSException;
import kernel.process.AbstractProcess;
import kernel.process.AbstractProcessHeader;

/**
 * Kill process.
 * For more see man() method.
 * @author Jaromir Lepic, Petr Hajek, Veronika Vencurikova
 *
 */
public class Kill extends AbstractProcess {

	public Kill(AbstractProcessHeader header, long pid) {
		super(header, pid);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String doJob(String input) throws OSException {
		if (this.params.size() == 0) throw new OSException(OSException.NO_ARGS);
		else if (this.params.size() > 1) throw new OSException(OSException.ERR_MANY_ARGS);
		
		long processID = 0;
		try {
			processID = Long.parseLong(this.params.get(0));
		} catch (NumberFormatException e) {
			throw new OSException(OSException.ERR_WRONG_ARGS);
		}
		
		if (processID == this.pid) return "Process " + processID + " doesn't exist.";
		
		if (processID == 0 && ProcessMemory.isKernelRunning()) {
			ProcessManager.getInstance().stop();
			return "Process " + processID + " was killed.";
		}
		else if (processID == 0 && !ProcessMemory.isKernelRunning()) return "Process " + processID + " doesn't exist.";
		
		AbstractProcess ap = ProcessMemory.findProgramWithID(processID);
		if (ap == null) return "Process " + processID + " doesn't exist.";
		ap.killProcess();
		
		return "Process " + processID + " was killed.";
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean needParams() {
		return true;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void kill() throws OSException {
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String continueJob() throws OSException {
		this.shouldEnd = true;
		return null;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected String finalizeJob() throws OSException {
		return null;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String man(String command) {
	String man = "";
			
			man += "    terminates a process\n";
			man += "\n";
			man += "Command syntax:\n";
			man += "    kill [PID]\n";
			man += "\n";
			man += "Examples:\n";
			man += "    kill 1\n";
			
			return man;
	}

}
